<?php

namespace App\Http\Controllers;

use App\Models\Message;
use App\Models\User;
use App\support\gateway\Gateway;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index(Request $request)
    {
        $roomId = $request->get('room_id', 1);
        session()->put('room_id', $roomId);
        return view('homeRoom');
    }

    public function init(Request $request)
    {

        //绑定用户
        $this->bind($request);

        //在线用户
        $this->users();
        // 显示历史记录
        $this->history();

        // 进入聊天室
        $this->login();
    }

    public function say(Request $request)
    {
        $data = array(
            'type' => 'say',
            'data' => array(
                'avatar' => Auth::user()->avatar(),
                'name' => Auth::user()->name,
                'content' => $request->input('content'),
                'time' => now()->format('Y-m-d H:i:s'),
            )
        );

        //私聊
        if ($request->user_id) {
            $data['data']['name'] = Auth::user()->name . ' 对 ' . User::find($request->user_id)->name . ' 说：';
            Gateway::sendToUid($request->user_id, json_encode($data));
            Gateway::sendToUid(Auth::id(), json_encode($data));

            //私聊信息，只发给对应用户，不存数据库了
            return;
        }


        try {
            Gateway::sendToGroup(session()->get('room_id') ,msg($data));
        } catch (\Exception $e) {
            dd($e);
        }

        Message::create([
            'user_id' => Auth::id(),
            'content' => $request->input('content'),
            'room_id' => session()->get('room_id')
        ]);
    }

    /**
     * 绑定uid 与 user id
     */
    private function bind($request)
    {
        $this->validate($request ,array(
            'client_id' => 'required'
        ));
        $id = Auth::id();
        $client_id = $request->get('client_id');
        Gateway::bindUid($client_id, $id);
        Gateway::joinGroup($client_id, session()->get('room_id'));
        Gateway::setSession($client_id, [
            'id' => $id,
            'avatar' => Auth::user()->avatar(),
            'name' => Auth::user()->name
        ]);
    }

    private function login()
    {
        $data = array(
            'type' => 'say',
            'data' => [
                'avatar' => Auth::user()->avatar(),
                'name' => Auth::user()->name,
                'content' => '进入了聊天室',
                'time' => now()->format('Y-m-d H:i:s'),
            ]
        );

        try {
            Gateway::sendToGroup(session()->get('room_id'), msg($data));
        } catch (\Exception $e) {
            return  response('消息发送失败', '500');
        }
    }

    private function history()
    {
        $data = array(
            'type' => 'history'
        );

        $messages = Message::with('user')->where('room_id', session()->get('room_id'))->orderBy('id', 'desc')->limit(5)->get();
        $data['data'] = $messages->map(function ($message) {
            return [
                'avatar' => $message->user->avatar(),
                'name' => $message->user->name,
                'content' => $message->content,
                'time' => $message->created_at->format("Y-m-d H:i:s")
            ];
        })
        ->toArray();
        try {
            Gateway::sendToUid(Auth::id(), msg($data));
        }catch (\Exception $e) {
            dd($e);
        }

    }

    private function users()
    {
        $data = array(
            'type' => 'users',
            'data' => Gateway::getClientSessionsByGroup(session()->get('room_id'))
        );

        try {
            Gateway::sendToGroup(session()->get('room_id'), msg($data));
        } catch (\Exception $e) {
            dd($e);
        }
    }
}
